package com.boot.controller;

import com.boot.CheckPermission;
import com.boot.entity.*;
import com.boot.service.IAccountManagementService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 账户管理Controller
 */
@Controller
@RequestMapping("/user")
public class AccountManagementController {

    public final IAccountManagementService service;

    public AccountManagementController(IAccountManagementService service) {
        this.service = service;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "redirect:tologin";
    }

    /**
     * 权限不足errorPage
     */
    @RequestMapping("/permissionDenied")
    public String permissionDenied() {
        return "commons/600";
    }

    //=============================================
    /**
     * 查看采购请求详细内容
     */
    @RequestMapping("/purchaseDetail")
    public String purchaseDetail(Integer id, Model model) {
        PurchapplyDetail purchaseDetail = service.findPurchapplyDetailById(id);
        Purchapply purchapply = service.findPurchapplyById(id);
        CoalQuality coalQuality = service.findCoalQualityById(id);
        model.addAttribute(purchaseDetail);
        model.addAttribute(purchapply);
        model.addAttribute(coalQuality);

        Company company = service.findCompanyById(purchaseDetail.getCompanyId());
        User applicantUser = service.findUserById(purchaseDetail.getApplicantId());
        User signerUser = service.findUserById(purchaseDetail.getApplicantId());
        model.addAttribute(company);
        model.addAttribute("applicantUser", applicantUser);
        model.addAttribute("signerUser", signerUser);
        return "purchapply_z_detail";
    }

    /**
     * 查看公司发布的采购请求
     */
    @RequestMapping("/purchaseManage")
    public String purchaseManage(Integer pageIndex, Integer pageSize, Model model, HttpSession session) {
        if (pageIndex == null) {
            pageIndex = 1;
        }
        if (pageSize == null) {
            pageSize = 6;
        }

        session.setAttribute("loginUser", service.findUserById(2));
        User user = (User) session.getAttribute("loginUser");

        PageHelper.startPage(pageIndex, pageSize);
        List<PurchapplyDetail> details = service.findPurchapplyDetailByCompanyId(user.getCompanyId());

        //装填公司采购申请列表
        List<Purchapply> purchapplies = new ArrayList<>();
        details.forEach(purchapplyDetail -> {
            Purchapply purchapply = service.findPurchapplyById(purchapplyDetail.getPurchapplyId());
            if (purchapply != null) {
                purchapplies.add(purchapply);
            }
        });
        model.addAttribute("purchapplies", purchapplies);

        //装填页面数据
        int count = service.findPurchapplyDetailCountByCompanyId(user.getCompanyId());
        int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        //分页数量
        model.addAttribute("pageNum", pageNum);
        //当前页面
        model.addAttribute("currentPage", pageIndex);
        //每页数据条数
        model.addAttribute("pageSize", pageSize);
        return "purchapply_z_list";
    }

    /**
     * 进入添加采购申请页
     */
    @CheckPermission({1})
    @RequestMapping("/add_request")
    public String addPurchaseRequest(Model model, HttpSession session) {
        //todo 去除下面这一条
        session.setAttribute("loginUser", service.findUserById(2));

        int nextId = service.nextPurchapplyID();
        User user = (User) session.getAttribute("loginUser");
        Company company = service.findCompanyById(user.getCompanyId());
        User qxuser = service.findUserById(company.getUserId());

        //单据编号
        model.addAttribute("document_number", company.getCompanyName() + "#" + nextId);
        //签发人
        model.addAttribute("qxuser", qxuser);
        //申请时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        model.addAttribute("time", format.format(new Date().getTime()));

        model.addAttribute(user);
        model.addAttribute(company);
        return "purchapply_z_add";
    }

    /**
     * 修改已驳回的采购申请
     */
    @CheckPermission({1})
    @RequestMapping("/modify_request")
    public String modifyPurchaseRequest(Integer id, Model model) {
        PurchapplyDetail purchaseDetail = service.findPurchapplyDetailById(id);
        Purchapply purchapply = service.findPurchapplyById(id);
        CoalQuality coalQuality = service.findCoalQualityById(id);
        model.addAttribute(purchaseDetail);
        model.addAttribute(purchapply);
        model.addAttribute(coalQuality);

        Company company = service.findCompanyById(purchaseDetail.getCompanyId());
        User applicantUser = service.findUserById(purchaseDetail.getApplicantId());
        User signerUser = service.findUserById(purchaseDetail.getApplicantId());
        model.addAttribute(company);
        model.addAttribute("applicantUser", applicantUser);
        model.addAttribute("signerUser", signerUser);

        return "purchapply_z_modify";
    }

    @CheckPermission({1})
    @RequestMapping("/request_perform_modify")
    @ResponseBody
    public Object performRequestModify(Purchapply purchapply, PurchapplyDetail purchapplyDetail, CoalQuality coalQuality,
                                       String createTime, String endTime, String jhStartTime, String jhEndTime,
                                       String detailRemark, String coalRemark) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        if (!"".equals(createTime) && createTime != null) {
            long create = dateFormat.parse(createTime).getTime();
            purchapplyDetail.setCreateDate(create);
        }
        if (!"".equals(endTime) && endTime != null) {
            long end = dateFormat.parse(endTime).getTime();
            purchapplyDetail.setDeadline(end);
        }
        if (!"".equals(jhStartTime) && jhStartTime != null) {
            long jhStart = dateFormat.parse(jhStartTime).getTime();
            purchapplyDetail.setJhTime(jhStart);
        }
        if (!"".equals(jhEndTime) && jhEndTime != null) {
            long jhEnd = dateFormat.parse(jhEndTime).getTime();
            purchapplyDetail.setJhDeadline(jhEnd);
        }

        //热卡值随便找了一个值顶替
        if (coalQuality.getQnetAr() != null)
            purchapply.setCalorieValue(coalQuality.getQnetAr().intValue());
        if (purchapplyDetail.getCoalClass() != null)
            purchapply.setCoalType(purchapplyDetail.getCoalClass());
        purchapply.setApprovalStatus("pending");
        if (purchapplyDetail.getCreateDate() != null)
            purchapply.setApprovalTime(purchapplyDetail.getCreateDate());

        purchapplyDetail.setRemark(detailRemark);
        coalQuality.setRemark(coalRemark);

        Map<String, String> map = new HashMap<>();
        try {
            int count = service.modifyPurchaseRequest(purchapply, purchapplyDetail, coalQuality);
            map.put("code", String.valueOf(count));
            map.put("msg", "修改成功");
        } catch (Exception e) {
            map.put("code", "-1");
            map.put("msg", "修改失败");
            e.printStackTrace();
        }
        return map;
    }

    @CheckPermission({1})
    @RequestMapping("/request_perform_delete")
    @ResponseBody
    public Object performRequestDelete(int id){
        Map<String, String> map = new HashMap<>();
        try {
            int count = service.deletePurchaseRequest(id);
            map.put("code", String.valueOf(count));
            map.put("msg", "删除成功");
        } catch (Exception e) {
            map.put("code", "-1");
            map.put("msg", "删除失败");
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 新建采购申请
     */
    @RequestMapping("/add_purchase")
    @ResponseBody
    public Object addPurchaseRequest(Purchapply purchapply, PurchapplyDetail purchapplyDetail, CoalQuality coalQuality,
                                     String createTime, String endTime, String jhStartTime, String jhEndTime,
                                     String detailRemark, String coalRemark) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        if (!"".equals(createTime) && createTime != null) {
            long create = dateFormat.parse(createTime).getTime();
            purchapplyDetail.setCreateDate(create);
        }
        if (!"".equals(endTime) && endTime != null) {
            long end = dateFormat.parse(endTime).getTime();
            purchapplyDetail.setDeadline(end);
        }
        if (!"".equals(jhStartTime) && jhStartTime != null) {
            long jhStart = dateFormat.parse(jhStartTime).getTime();
            purchapplyDetail.setJhTime(jhStart);
        }
        if (!"".equals(jhEndTime) && jhEndTime != null) {
            long jhEnd = dateFormat.parse(jhEndTime).getTime();
            purchapplyDetail.setJhDeadline(jhEnd);
        }

        //热卡值随便找了一个值顶替
        if (coalQuality.getQnetAr() != null)
            purchapply.setCalorieValue(coalQuality.getQnetAr().intValue());
        if (purchapplyDetail.getCoalClass() != null)
            purchapply.setCoalType(purchapplyDetail.getCoalClass());
        purchapply.setApprovalStatus("pending");
        if (purchapplyDetail.getCreateDate() != null)
            purchapply.setApprovalTime(purchapplyDetail.getCreateDate());

        purchapplyDetail.setRemark(detailRemark);
        coalQuality.setRemark(coalRemark);

        Map<String, String> map = new HashMap<>();
        try {
            int count = service.addPurchaseRequest(purchapply, purchapplyDetail, coalQuality);
            map.put("code", String.valueOf(count));
            map.put("msg", "发起采购成功");
        } catch (Exception e) {
            map.put("code", "-1");
            map.put("msg", "发起采购失败");
            e.printStackTrace();
        }
        return map;
    }

    //=========================================================================

    /**
     * 查看用户列表
     */
    @CheckPermission({0, 1, 2})
    @RequestMapping("/query")
    public String userManage(Integer pageIndex, Integer pageSize, String key, Model model) {
        if (pageIndex == null) {
            pageIndex = 0;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        if (key != null && !"".equals(key.trim())) {
            model.addAttribute("key", key);
        }

        /**
         * PageHelper.startPage(0, 6) <- 该语句后的第一次Select将只会获取第0页共6条的数据
         */
        PageHelper.startPage(pageIndex, pageSize);
        List<User> users = service.findAllUser(key);
        model.addAttribute("users", users);

        int count = service.findUserCount(key);
        int pageNum = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        //        //分页数量
        model.addAttribute("pageNum", pageNum);
        //当前页面
        model.addAttribute("currentPage", pageIndex);
        //页面数据条数
        model.addAttribute("pageSize", pageSize);
        return "user";
    }

    /**
     * 查看用户个人信息
     */
    @RequestMapping("/info")
    public String userInfo(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("loginUser");
        if (user != null) {
            model.addAttribute("user", user);
        } else {
            throw new RuntimeException("用户未登录");
        }
        return "user_info";
    }

    /**
     * 添加新用户
     */
    @RequestMapping("/add_user")
    public String addUser(Model model) {
        List<Company> companies = service.findAllCompany();
        List<Department> departments = service.findAllDepartment();

        model.addAttribute("companies", companies);
        model.addAttribute("departments", departments);
        return "user_add_user";
    }

    /**
     * 查看用户公司信息
     */
    @RequestMapping("/company_info")
    public String companyInfo(HttpServletRequest request, Model model) {
        User user = (User) request.getSession().getAttribute("loginUser");
        if (user == null) {
            throw new RuntimeException("用户未登录");
        }

        Company company = service.findCompanyById(user.getCompanyId());
        Company parentCompany = service.findCompanyById(company.getParentCompanyId());
        System.out.println(parentCompany);
        System.out.println(company.getParentCompanyId());

        User header = service.findUserById(company.getUserId());

        model.addAttribute("company", company);
        model.addAttribute("parentCompany", parentCompany);
        model.addAttribute("header", header);

        return "user_company_info";
    }

    /**
     * 用户信息修改
     */
    @RequestMapping("/info_modify")
    public String infoModify(Integer userId, Model model) {
        User user = service.findUserById(userId);
        model.addAttribute("user", user);
        return "user_info_modify";
    }

    /**
     * 管理员修改他人密码
     */
    @RequestMapping("/password_modify")
    public String passwordModify(Integer userId, Model model) {
        User user = service.findUserById(userId);
        model.addAttribute("user", user);
        return "user_password_modify";
    }

    /**
     * 修改用户自己的密码
     */
    @RequestMapping("/self_password_modify")
    public String selfPasswordMofify(@SessionAttribute("loginUser") User user, Model model) {
        model.addAttribute("user", user);
        return "user_self_password_modify";
    }

    /**
     * JavaScript异步更新用户列表接口
     */
    @RequestMapping("/json")
    @ResponseBody
    public Object userManage(Integer pageIndex, Integer pageSize, String key) {
        if (pageIndex == null) {
            pageIndex = 0;
        }
        if (pageSize == null) {
            pageSize = 6;
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<User> users = service.findAllUser(key);
        return users;
    }

    /**
     * 更新用户信息的接口
     */
    @RequestMapping("/update")
    @ResponseBody
    public Object infoUpdate(User user) {
        HashMap<String, Object> map = new HashMap<>(2);
        if (user == null) {
            map.put("msg", "要更新的用户为空");
            map.put("code", "-1");
        } else {
            int count = service.updateUser(user);
            map.put("msg", "修改用户信息成功");
            map.put("code", count);
        }
        return map;
    }

    @RequestMapping("/passwordModify")
    @ResponseBody
    public Object passwordUpdate(User user, String old_password) {
        HashMap<String, Object> map = new HashMap<>(2);
        if (user == null) {
            map.put("msg", "要更新的用户为空");
            map.put("code", "-1");
        } else if (user.getPwd() != null && !"".equals(user.getPwd())) {
            String oldPassword = service.findUserById(user.getId()).getPwd();
            if (!oldPassword.equals(old_password)) {
                map.put("msg", "密码错误");
                map.put("code", "-1");
            } else {
                int count = service.updateUser(user);
                map.put("msg", "修改用户密码成功");
                map.put("code", count);
            }
        }
        return map;
    }

    /**
     * 添加用户的接口
     */
    @RequestMapping("/add")
    @ResponseBody
    public Object addUser(User user) {
        HashMap<String, String> map = new HashMap<>(2);
        if (user == null) {
            map.put("msg", "要添加的用户为空");
            map.put("code", "-1");
        } else if (service.findUserByUserName(user.getUsername()) != null) {
            map.put("msg", "用户名已经存在");
            map.put("code", "-1");
        } else {
            int count = service.addUser(user);
            map.put("msg", "添加成功");
            map.put("code", String.valueOf(count));
        }
        return map;
    }

    /**
     * 删除用户的接口
     */
    @RequestMapping("/del")
    @ResponseBody
    public Object delUser(Integer id) {
        HashMap<String, Object> map = new HashMap<>(2);
        if (id == null) {
            map.put("msg", "要删除的用户id为空");
            map.put("code", "-1");
        } else {
            int count = service.delUser(id);
            map.put("msg", "删除成功");
            map.put("code", count);
        }
        return map;
    }
}
